package com.sky.utils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
public class CustomTimeSerializer extends JsonSerializer<LocalDateTime> {
    @Override
    public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        DateTimeFormatter hourFormatter = new DateTimeFormatterBuilder()
                .appendValue(ChronoField.HOUR_OF_DAY)
                .appendLiteral("h")
                .toFormatter();

        DateTimeFormatter minuteFormatter = new DateTimeFormatterBuilder()
                .appendValue(ChronoField.MINUTE_OF_HOUR)
                .appendLiteral("m")
                .toFormatter();

        DateTimeFormatter hourAndMinuteFormatter = new DateTimeFormatterBuilder()
                .appendValue(ChronoField.HOUR_OF_DAY)
                .appendLiteral("h")
                .appendValue(ChronoField.MINUTE_OF_HOUR)
                .appendLiteral("m")
                .toFormatter();

        String formattedTime;
        if (value.getHour() == 0) {
            formattedTime = value.format(minuteFormatter);
        } else if (value.getMinute() == 0) {
            formattedTime = value.format(hourFormatter);
        } else {
            formattedTime = value.format(hourAndMinuteFormatter);
        }

        gen.writeString(formattedTime);
    }
}